package com.tbit.uqbike.client.handler;

import com.tbit.uqbike.client.common.ResultCode;
import com.tbit.uqbike.client.common.ResultMsg;
import com.tbit.uqbike.client.dao.core.BorrowCheckConfigDao;
import com.tbit.uqbike.client.handler.borrowbikehandler.AbstractCheckHandler;
import com.tbit.uqbike.client.pojo.borrowbike.BorrowCheckConfig;
import com.tbit.uqbike.client.vo.borrow.BorrowBikeVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lh2
 * @ClassName: CheckService
 * @Description: TODO
 * @date 2023-07-26 04:17:03
 */
@Slf4j
@Component
public class CheckService {
    /**
     * 使用Spring注入:所有继承了AbstractCheckHandler抽象类的Spring Bean都会注入进来。Map的Key对应Bean的name,Value是name对应相应的Bean
     */
    @Resource
    private Map<String, AbstractCheckHandler> handlerMap;
    @Resource
    private BorrowCheckConfigDao borrowCheckConfigMapepr;
    @Resource
    private CheckClient checkClient;

    /**
     * 参数校验：责任链模式
     *
     * @param param
     * @return
     */
    public ResultMsg checkChain(BorrowBikeVO vo, String serialNO) {
        // 获取处理器配置
        List<BorrowCheckConfig> handlerConfigs = borrowCheckConfigMapepr.selectAll();
        // 获取处理器
        AbstractCheckHandler handler = this.getHandler(handlerConfigs, 0);
        // 执行处理器链路
        ResultMsg executeChainResult = checkClient.executeChain(handler, vo, serialNO);
        if (executeChainResult.getRet() != ResultCode.SUCCESS.getCode()) {
            log.info("借车校验处理器链执行失败，ResultCode={}，ResultMsg=={}", executeChainResult.getCode(),
                    executeChainResult.getMsg());
            return executeChainResult;
        }
        // 处理器链路全部成功
        return ResultMsg.success();
    }

    /**
     * 获取处理器
     */
    private AbstractCheckHandler getHandler(List<BorrowCheckConfig> configList, int orderNum) {
        // 配置检查：没有配置处理器链路，则不执行校验逻辑
        if (configList == null || configList.size() == 0 || orderNum > configList.size()) {
            return null;
        }
        // 配置错误
        String handler = configList.get(orderNum).getHandlerName();
        if (StringUtils.isBlank(handler)) {
            return null;
        }
        // 配置了不存在的处理器
        AbstractCheckHandler abstractCheckHandler = handlerMap.get(configList.get(orderNum).getHandlerName());
        if (Objects.isNull(abstractCheckHandler)) {
            return null;
        }
        // 处理器设置配置Config
        abstractCheckHandler.setConfig(configList.get(orderNum));
        // 递归设置链路处理器，这里的orderNum取值为0-8， configList.size() 为9
        if (orderNum < configList.size() - 1) {
            abstractCheckHandler.setNextHandler(this.getHandler(configList, orderNum + 1));
        }
        return abstractCheckHandler;
    }
}
